#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import logging, datetime
from logging.handlers import TimedRotatingFileHandler

import time
import threading


class XLogger(object):
    _instance_lock = threading.Lock()

    def __init__(self, p_level=logging.NOTSET, p_name_key_word=None):
        """
        :param p_level
        :param p_name_key_word
        """
        time.sleep(1)

        # all-in-one log
        f = 'log_%s.txt' % (p_name_key_word) if p_name_key_word is not None else 'log.txt'
        logging.basicConfig(filename=f, format='%(asctime)s - %(levelname)s - %(message)s', level=p_level)

        # log format
        self.logger = logging.getLogger(__name__)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        # rolling log
        t = (datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))
        f = "log_%s_%s.txt" % (p_name_key_word, t) if p_name_key_word is not None else "log_%s.txt" % t
        aHandler = TimedRotatingFileHandler(filename=f, when='D', encoding="utf-8")
        aHandler.setLevel(p_level)
        aHandler.setFormatter(formatter)

        bHandler = logging.StreamHandler()
        bHandler.setLevel(p_level)
        bHandler.setFormatter(formatter)

        self.logger.addHandler(aHandler)
        self.logger.addHandler(bHandler)

    @classmethod
    def getInstance(cls, *args, **kwargs):
        with XLogger._instance_lock:
            if not hasattr(XLogger, "_instance"):
                XLogger._instance = XLogger(*args, **kwargs)
        return XLogger._instance
